import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Form, Input, Button, Modal } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import FormItem from 'antd/es/form/FormItem';
import { getUserPage, DataType, getUserApi } from '@/service/user';

const queryPage: getUserPage = {
  name: '',
  current: 1,
  size: 10,
  sortField: '',
  sortOrder: '',
};

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const { Search } = Input;

const App: React.FC = () => {
  const [data, setData] = useState<DataType[]>();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '用户账户',
        dataIndex: 'account',
        sorter: true,
        render: (account) => `${account}`,
        width: '15%',
      },
      {
        title: '用户名',
        dataIndex: 'userName',
        render: (userName) => `${userName}`,
        width: '10%',
      },
      {
        title: '角色',
        dataIndex: 'role',
        sorter: true,
        render: (role) => (role === 1 ? '餐厅管理员' : '普通用户'),
        width: '10%',
      },
      {
        title: '操作',
        width: '15%',
        render: (_, record) => (
          <>
            <Button>{record.state === 0 ? '恢复' : '停用'}</Button>
          </>
        ),
      },
    ],
    [],
  );

  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);
    try {
      const res = await getUserApi(queryPage);
      setData(res.records);
      setTableParams((prevParams) => ({
        ...prevParams,
        pagination: {
          current: res.current,
          pageSize: res.size,
          total: res.total,
          ...prevParams.pagination,
        },
      }));
    } finally {
      setLoading(false);
    }
  }, [tableParams]);

  //监听tableParams的变化
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(tableParams)]);

  //监听queryPage的变化
  const handleTableChange = useCallback(
    (
      pagination: TablePaginationConfig = {},
      filters: Record<string, FilterValue> = {},
      sorter: SorterResult<DataType> = {},
    ) => {
      setTableParams({
        pagination,
        filters,
        ...sorter,
      });
      queryPage.current = (pagination && Number(pagination.current)) || 1;
      queryPage.size = (pagination && Number(pagination.pageSize)) || 10;
      //如果为undefined则转换为'' String类型
      queryPage.sortField = sorter && sorter.field ? String(sorter.field) : '';
      queryPage.sortOrder =
        sorter && sorter.order === 'descend'
          ? 'desc'
          : sorter && sorter.order === 'ascend'
          ? 'asc'
          : '';
    },
    [tableParams],
  );

  //搜索
  const onSearch = useCallback(
    (value: string) => {
      queryPage.name = value;
      handleTableChange();
    },
    [handleTableChange],
  );

  return (
    <div>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        pagination={tableParams.pagination}
        scroll={{ y: 530 }}
      />
    </div>
  );
};
export default App;
